/*************************************************************************
	> File Name: 004.weighted_quick_union_with_path_compression.java
	> Author: Maureen 
	> Mail: Maureen@qq.com 
	> Created Time: 四 10/ 7 22:18:10 2021
 ************************************************************************/

public class WeightedQuickUnionWithPathCompressionUF
{
    private int[] id;
    private int[] sz;
    private int count;

    public WeightedQuickUnionWithPathCompressionUF(int n)
    {
        count = n;
        id = new int[n];
        for (int i = 0; i < n; i++) id[i] = i;
        sz = new int[n];
        for (int i = 0; i < n; i++) sz[i] = 1;
    }


    public int count() 
    {
        return count;
    }

    public boolean connected(int p, int q) 
    {
        return find[p] == find[q];
    }

    private int find(int p)
    {
        while (p != id[p]) {
            id[p] = id[id[p]];
            p = id[p];
        }
        return p;
    }

    public void union(int p, int q) 
    {
        int i = find(p);
        int j = find(q);
        if (i == j) return ;
        if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; }
        else { id[j] = i; sz[i] += sz[j]; }
        count--;
    }
}
